package com.sinba.common.system.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.sinba.common.dto.PageDTO;
import com.sinba.common.system.dao.IGenerateRegisterCodeDao;
import com.sinba.common.user.dto.RegisterCodeDTO;
import com.sinba.common.user.entity.RegisterCode;

public class GenerateRegisterCodeService implements IGenerateRegisterCodeService {

	@Autowired
	private IGenerateRegisterCodeDao generateRegisterCodeDao;
	
	
	public PageDTO searchCode(RegisterCodeDTO dto, int start, int limit, String sidx, String sord) {
		PageDTO pDto = generateRegisterCodeDao.findPager(dto, start, limit, sidx, sord);
		List<RegisterCode> lists = (List<RegisterCode>)pDto.getData();
		List<RegisterCodeDTO> dtos = new ArrayList<RegisterCodeDTO>();
		for(RegisterCode code : lists){
			RegisterCodeDTO codedto = new RegisterCodeDTO();
			RegisterCodeDTO.entity2dto(code, codedto );
			dtos.add(codedto);
		}
		pDto.setData(dtos);
		return pDto;
	}

	/**
	 * 生成注册码
	 */
	public List<RegisterCodeDTO> generateCode(int num, String remark) {
		if (num == 0 || !StringUtils.hasText(remark)) {
			return null;
		}
		List<RegisterCodeDTO> dtos = new ArrayList<RegisterCodeDTO>();
		while (num > 0) {
			RegisterCode code = new RegisterCode();
			String generateCode = generateCode(6, 2);			//生成激活码
			String generateToken = generateToken(8);			//生成凭证
			RegisterCode dbCode = generateRegisterCodeDao.findUniqueBy("code", generateCode);
			RegisterCode dbToken = generateRegisterCodeDao.findUniqueBy("token", generateToken);
			if(dbCode != null || dbToken != null){
				continue;
			}
			if (dbCode == null && dbToken == null) {
				code.setCode(generateCode);
				code.setRemark(remark);
				code.setCreateTime(new Date());
				code.setToken(generateToken);
				// 未使用、已使用、已禁用（未使用）
				code.setStatus(IGenerateRegisterCodeService.NOT_USE);
				generateRegisterCodeDao.save(code);
			}

			RegisterCodeDTO dto = new RegisterCodeDTO();
			RegisterCodeDTO.entity2dto(code, dto);
			dtos.add(dto);
			num--;
		}
		return dtos;
	}

	
	// 验证激活码的合法性
	public Boolean registerCodeVerification(String code) {
		Boolean flag = false;
		RegisterCode dbCode = generateRegisterCodeDao.findUniqueBy("code", code);
		if (IGenerateRegisterCodeService.NOT_USE.equals(dbCode.getStatus())) {
			flag = true;
		}
		return flag;
	}
	
	/**
	 * 使用注册码
	 */
	public Boolean userRegisterCode(String loginName, String code) {
		Boolean flag = false;
		RegisterCode dbCode = generateRegisterCodeDao.findUniqueBy("code", code);
		if (IGenerateRegisterCodeService.NOT_USE.equals(dbCode.getStatus())) {
			dbCode.setLoginName(loginName);
			dbCode.setUseTime( new Date() );
			dbCode.setStatus(IGenerateRegisterCodeService.USED);
			generateRegisterCodeDao.update(dbCode);
			flag = true;
		}
		return flag;
	}

	/**
	 * 禁用激活码
	 */
	public void banRegisterCode(String code) {
		RegisterCode dbCode = generateRegisterCodeDao.findUniqueBy("code", code);
		if(IGenerateRegisterCodeService.NOT_USE.equals(dbCode.getStatus())){
			dbCode.setStatus(IGenerateRegisterCodeService.SOTP_USE);
			generateRegisterCodeDao.update(dbCode);
		}
	}
	
	/**
	 * 禁用激活码
	 */
	public void banRegisterCode(Long[] ids) {
		List<RegisterCode> codes = generateRegisterCodeDao.findByIds(ids);
		for(RegisterCode code : codes){
			if(IGenerateRegisterCodeService.NOT_USE.equals(code.getStatus())){
				code.setStatus(IGenerateRegisterCodeService.SOTP_USE);
				generateRegisterCodeDao.update(code);
			}
		}
	}	

	/**
	 * 生成code算法
	 * 
	 * @param num
	 * @return
	 */
	private String generateCode(int num, int englishWordNum) {
		StringBuffer sb = new StringBuffer();
		int limit = 0;
		while (num > 0) {
			Object obj = generateSingleCode(new Random().nextInt(2));
			if (obj instanceof Character) {
				limit++;
			}
			if (englishWordNum >= limit) {
				continue;
			}
			sb.append(obj);
			num--;
		}
		return sb.toString();
	}

	private Object generateSingleCode(int type) {
		Object obj = null;
		switch (type) {
		case 0:
			obj = (char) (new Random().nextInt(26) + 65);
			break;
		case 1:
			obj = new Random().nextInt(10);
			break;
		default:
			throw new IllegalArgumentException("参数有误");
		}
		return obj;
	}
	
	/**
	 * 生成凭证
	 * @param size
	 * @return
	 */
	private String generateToken(int size){
		StringBuilder sb = new StringBuilder();
		int length = 1;
		if(size <= 0){
			throw new IllegalArgumentException("输入的长度不能小于1");
		}
		while(size >= length){
			int num = new Random().nextInt(10);
			sb.append(num);
			length++;
		}
		return sb.toString();
	}
	
	/**
	 * 批量删除
	 * @param ids
	 */
	public void deleRegisterCodes(Long[] ids){
		generateRegisterCodeDao.deleteByIds(ids);
	}
	
	/**
	 * 删除激活码
	 */
	public void deleRegisterCode(String code) {
		RegisterCode dbCode = generateRegisterCodeDao.findUniqueBy("code", code);
		if(dbCode != null){
			generateRegisterCodeDao.delete(dbCode);
		}
	}

	/**
	 * 获取凭证
	 */
	public RegisterCodeDTO getToken() {
		RegisterCodeDTO page = new RegisterCodeDTO();
		page.setStatus(GenerateRegisterCodeService.NOT_USE);//没用使用和禁用的激活码
		PageDTO pageDTO = generateRegisterCodeDao.findPager(page , 0, 1, "createTime", "desc");
		RegisterCode code = (RegisterCode)pageDTO.getData().get(0);
		RegisterCodeDTO dto = new RegisterCodeDTO();
		RegisterCodeDTO.entity2dto(code, dto);
		return dto;
	}




}
